<?php

namespace Sdk\lib;

use Exception;

class DiscuzRestful {
	private static $_instance;

	var $site;
	var $appid;
	var $secret;
	var $token;

	public static function getInstance($site, $appid, $secret) {
		self::$_instance = new self($site, $appid, $secret);
		return self::$_instance;
	}

	public function __construct($site, $appid, $secret) {
		$this->site = $site;
		$this->appid = $appid;
		$this->secret = $secret;
	}

	public function request($uri, $post) {
		$nonce = rand(10000, 20000);
		$t = time();
		$headers = array(
			'appid' => $this->appid,
			'nonce' => $nonce,
			't' => $t,
			'sign' => base64_encode(hash('sha256', $nonce . $t . $this->secret)),
		);

		if ($this->token) {
			$headers['token'] = $this->token;
		}

		$headersFmt = array();
		foreach ($headers as $name => $value) {
			$canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
			$headersFmt[] = $canonicalName . ': ' . $value;
		}

		$ch = curl_init();
		curl_setopt_array($ch, array(
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HTTPHEADER => $headersFmt,
			CURLOPT_URL => $this->site . '/api/restful/?' . $uri,
			CURLOPT_POST => 'POST',
			CURLOPT_POSTFIELDS => $post,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_SSL_VERIFYPEER => false,
		));
		$response = curl_exec($ch);

		$responseBody = json_decode($response, true);
		if (!$responseBody) {
			throw new Exception('client site response is empty');
		}
		return $responseBody;
	}
}